import { useMutation } from "@apollo/react-hooks";
import gql from "graphql-tag";
import { notification } from "antd";

import { usePageContext } from "./useContext";
import { QUERY } from "./useTable";
import { handleErrors } from "../../../utils/handleErrors";
import { SYS_ROLES } from "../../SysUser/hooks/useRoles";

const DELETE = gql`
  mutation DeleteSysRoles($ids: [String!]!) {
    deleteSysRoles(ids: $ids) {
      count
    }
  }
`;

export const useDelete = () => {
  const {
    state: { query },
    dispatch
  } = usePageContext();

  const [deleteSysRoles] = useMutation(DELETE, {
    onCompleted: ({ deleteSysRoles }) => {
      if (deleteSysRoles) {
        notification.success({
          message: `已删除${deleteSysRoles.count}个角色！`
        });
      }
    },
    onError: ({ graphQLErrors, networkError }) => {
      handleErrors({ graphQLErrors, networkError });
    },
    refetchQueries: [
      {
        query: QUERY,
        variables: {
          query
        }
      },
      { query: SYS_ROLES }
    ]
  });

  const handleDelete = ids => {
    deleteSysRoles({ variables: { ids } });
  };

  return {
    handleDelete
  };
};
